<?php

App::uses('AppController', 'Controller');

class ShopController extends AppController {

    public $components = array(
        'Cart',
        'Paypal',
        'AuthorizeNet',
        'Pagseguro.Carrinho'
    );
    public $uses = array('Product', 'Order', 'OrderItem');

    public function beforeFilter() {
        parent::beforeFilter();
        $this->disableCache();
        //$this->Security->validatePost = false;
    }

    public function clear() {
        $this->Cart->clear();
        $this->Session->setFlash('All item(s) removed from your shopping cart', 'flash_error');
        return $this->redirect('/');
    }

    public function add() {
        if ($this->request->is('post')) {

            $id = $this->request->data['Product']['id'];

            $quantity = isset($this->request->data['Product']['quantity']) ? $this->request->data['Product']['quantity'] : null;

            $productmodId = isset($this->request->data['mods']) ? $this->request->data['mods'] : null;

            $product = $this->Cart->add($id, $quantity, $productmodId);
        }
        if (!empty($product)) {
            $this->Session->setFlash($product['Product']['name'] . ' ' . __('was added to your shopping cart') . '.', 'flash_success');
        } else {
            $this->Session->setFlash('Unable to add this product to your shopping cart.', 'flash_error');
        }
        $this->redirect($this->referer());
    }

    public function itemupdate() {
        if ($this->request->is('ajax')) {

            $id = $this->request->data['id'];

            $quantity = isset($this->request->data['quantity']) ? $this->request->data['quantity'] : null;

            if (isset($this->request->data['mods']) && ($this->request->data['mods'] > 0)) {
                $productmodId = $this->request->data['mods'];
            } else {
                $productmodId = null;
            }

            $product = $this->Cart->add($id, $quantity, $productmodId);
        }
        $cart = $this->Session->read('Shop');
        echo json_encode($cart);
        $this->autoRender = false;
    }

    public function update() {
        $this->Cart->update($this->request->data['Product']['id'], 1);
    }

    public function remove($id = null) {
        $product = $this->Cart->remove($id);
        if (!empty($product)) {
            $this->Session->setFlash($product['Product']['name'] . ' was removed from your shopping cart', 'flash_error');
        }
        return $this->redirect(array('action' => 'cart'));
    }

    public function cartupdate() {
        if ($this->request->is('post')) {
            foreach ($this->request->data['Product'] as $key => $value) {
                $p = explode('-', $key);
                $p = explode('_', $p[1]);
                $this->Cart->add($p[0], $value, $p[1]);
            }
            $this->Session->setFlash('Shopping Cart is updated.', 'flash_success');
        }
        return $this->redirect(array('action' => 'cart'));
    }

    public function cart() {
        $shop = $this->Session->read('Shop');
        $this->set(compact('shop'));
    }

    public function login() {

        if ($this->Session->read('Auth.User.role') != '' AND $this->Session->read('Auth.User.role') == 'customer') {
            return $this->redirect('/shop/address');
        }
    }

    public function address() {
        $shop = $this->Session->read('Shop');
        if (!$shop['Order']['total']) {
            return $this->redirect('/');
        }

        if ($this->Session->read('Auth.User.role') != '' AND $this->Session->read('Auth.User.role') != 'customer') {
            return $this->redirect('/');
        }

        if ($this->request->is('post')) {
            $this->loadModel('Order');
            $this->Order->set($this->request->data);
            if ($this->Order->validates()) {
                $order = array_merge($this->request->data['Order'], $this->request->data['Client']);
                $order['order_type'] = 'creditcard';
                $this->Session->write('Shop.Order', array_merge($order, $shop['Order']));
                return $this->redirect(array('action' => 'review'));
            } else {
                $this->Session->setFlash('The form could not be saved. Please, try again.', 'flash_error');
            }
        }
        if (!empty($shop['Order'])) {
            $this->request->data['Order'] = $shop['Order'];
        }
        $this->loadModel('Client');
        $this->request->data = array_merge($this->request->data, $this->Client->findByUserId($this->Session->read('Auth.User.id')));
    }

    public function review() {

        $shop = $this->Session->read('Shop');
        if (empty($shop)) {
            return $this->redirect('/');
        }
        if ($this->request->is('post')) {

            $this->loadModel('Order');
            $this->request->data['Order'] = $shop['Order'];
            $this->Order->set($this->request->data);
            if ($this->Order->validates()) {
                $order = $shop;
                $order['Order']['status'] = 1;

                $save = $this->Order->save($order);
                $id = $this->Order->id;
                $shop['Order']['id'] = $id;
                if ($save) {
                    $this->set(compact('shop'));
                    App::uses('CakeEmail', 'Network/Email');
                    $email = new CakeEmail();
                    $email->config(
                            array(
                                'username' => Configure::read('Settings.USERNAME'),
                                'transport' => Configure::read('Settings.TRANSPORT'),
                                'port' => Configure::read('Settings.PORT'),
                                'password' => Configure::read('Settings.PASSWORD'),
                                'log' => Configure::read('Settings.LOG'),
                                'charset' => Configure::read('Settings.CHARSET'),
                                'headerCharset' => Configure::read('Settings.HEADERCHARSET'),
                                'host' => Configure::read('Settings.DOMAIN'),
                            )
                    );
                    $email->from(Configure::read('Settings.ADMIN_EMAIL'))
                            ->cc(Configure::read('Settings.ADMIN_EMAIL'))
                            ->to($shop['Order']['email'])
                            ->subject('Shop Order')
                            ->template('order')
                            ->emailFormat('text')
                            ->viewVars(array('shop' => $shop))
                            ->send();
                    $this->checkout($shop);
                } else {
                    $errors = $this->Order->invalidFields();
                    $this->set(compact('errors'));
                }
            }
            $shop = $this->Order->findById($id);
        }

        $this->set(compact('shop'));
    }

    private function __setOrders($shop, $type) {
        $shop['Order']['order_type'] = $type;
        $this->Session->write('Shop.Order', $shop['Order']);
    }

    public function success() {
        $shop = $this->Session->read('Shop');
        $this->Cart->clear();
        if (empty($shop)) {
            return $this->redirect('/');
        }
        $this->set(compact('shop'));
    }

    public function checkout($shop) {
        foreach ($shop['OrderItem'] as $key => $value) {
            $shop['OrderItem'][$key]['order_id'] = $shop['Order']['id'];
            $this->Carrinho->adicionarItem($value['product_id'], $value['name'], $value['price'], ((int) $value['weight']) * 1000, $value['quantity']);
        }
        $this->OrderItem->save($shop);
        
        $this->Carrinho->setUrlRetorno(Router::url('/shop/retorno', true));
        $this->Carrinho->setContatosComprador($shop['Order']['first_name'] . ' ' . $shop['Order']['last_name'], $shop['Order']['email'], '16', '39191956');
        $this->Carrinho->setEnderecoComprador($shop['Order']['shipping_zip'], $shop['Order']['billing_address'], '109', '', 'Vila Guiomar', 'Ribeirão Preto', 'SP');
        $this->Carrinho->setTipoFrete('SEDEX');
        $this->Carrinho->setValorTotalFrete('0.01');
        $this->Carrinho->setTipoPagamento('BOLETO');
        $this->__setOrders($shop, 'pagseguro');

        if ($result = $this->Carrinho->finalizaCompra()) {
            $this->redirect($result);
        }
    }

    /**
     * Utilizado para retorno e consulta por código
     */
    public function retorno() {
        $idTransacao = $this->params['url']['transaction_id'];

        if ($this->Carrinho->obterInformacoesTransacao($idTransacao)) {
            $dadosUsuario = $this->Carrinho->obterDadosUsuario();
            debug($dadosUsuario);

            $statusTransacao = $this->Carrinho->obterStatusTransacao();
            debug($statusTransacao);

            $dadosPagamento = $this->Carrinho->obterDadosPagamento();
            debug($dadosPagamento);

            $dataTransacao = $this->Carrinho->obterDataTransacao();
            debug($dataTransacao);

            $valores = $this->Carrinho->obterValores();
            debug($valores);
            return $this->redirect(array('action' => 'success'));
        }
    }

}
